<template>
  <div class="home-page">
    <!-- 英雄区域 -->
    <section class="hero-section">
      <div class="hero-container">
        <div class="hero-content">
          <div class="hero-text">
            <h1 class="hero-title">
              <span class="gradient-text">智能代码生成</span>
              <br />
              让创意瞬间成为现实
            </h1>
            <p class="hero-description">
              通过AI对话，快速生成高质量的Web应用。无需复杂的编程知识，
              只需描述你的想法，AI将为你创建完整的应用程序。
            </p>

            <!-- 主要输入区域 -->
            <div class="prompt-input-section">
              <div class="input-container">
                <a-textarea
                  v-model:value="userPrompt"
                  placeholder="描述你想要创建的应用，例如：创建一个在线待办事项管理工具..."
                  :rows="4"
                  class="prompt-input"
                  :maxlength="500"
                />
                <div class="input-footer">
                  <div class="input-stats">
                    <span class="char-count">{{ userPrompt.length }}/500</span>
                  </div>
                  <a-button
                    type="primary"
                    size="large"
                    :loading="creating"
                    :disabled="!userPrompt.trim()"
                    @click="handleCreateApp"
                    class="create-btn"
                  >
                    <RocketOutlined />
                    开始创建
                  </a-button>
                </div>
              </div>

              <!-- 快速模板 -->
              <div class="quick-templates">
                <div class="templates-label">快速开始：</div>
                <div class="template-tags">
                  <a-tag
                    v-for="template in quickTemplates"
                    :key="template.id"
                    class="template-tag"
                    @click="handleSelectTemplate(template)"
                  >
                    <component :is="template.icon" />
                    {{ template.name }}
                  </a-tag>
                </div>
              </div>
            </div>
          </div>

          <div class="hero-visual">
            <div class="code-preview">
              <div class="code-window">
                <div class="window-header">
                  <div class="window-controls">
                    <span class="control red"></span>
                    <span class="control yellow"></span>
                    <span class="control green"></span>
                  </div>
                  <div class="window-title">AI 生成代码</div>
                </div>
                <div class="code-content">
                  <pre class="code-block">
<span class="code-comment">// AI 正在为你生成代码...</span>
<span class="code-keyword">import</span> <span class="code-string">React</span> <span class="code-keyword">from</span> <span class="code-string">'react'</span>

<span class="code-keyword">function</span> <span class="code-function">App</span>() {
  <span class="code-keyword">return</span> (
    <span class="code-tag">&lt;div</span> <span class="code-attr">className</span>=<span class="code-string">"app"</span><span class="code-tag">&gt;</span>
      <span class="code-tag">&lt;h1&gt;</span>你的应用<span class="code-tag">&lt;/h1&gt;</span>
    <span class="code-tag">&lt;/div&gt;</span>
  )
}
                  </pre>
                  <div class="typing-cursor"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 统计数据 -->
    <section class="stats-section">
      <div class="stats-container">
        <div class="stat-item">
          <div class="stat-number">{{ stats.appsCreated }}</div>
          <div class="stat-label">应用已创建</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ stats.activeUsers }}</div>
          <div class="stat-label">活跃用户</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ stats.deployments }}</div>
          <div class="stat-label">成功部署</div>
        </div>
        <div class="stat-item">
          <div class="stat-number">{{ stats.satisfaction }}%</div>
          <div class="stat-label">用户满意度</div>
        </div>
      </div>
    </section>

    <!-- 我的应用区域 -->
    <section v-if="loginUserStore.loginUser.id" class="my-apps-section">
      <div class="section-header">
        <h2 class="section-title">我的作品</h2>
        <a-button type="link" @click="loadMyApps">
          <ReloadOutlined />
          刷新
        </a-button>
      </div>

      <div class="apps-grid">
        <AppCard
          v-for="app in myApps.records"
          :key="app.id"
          :app="app"
          :featured="false"
          :show-user="false"
          :show-public-toggle="true"
          :current-user-id="loginUserStore.loginUser.id"
          @chat="handleAppChat"
          @view="handleAppView"
          @edit="handleAppEdit"
          @delete="handleAppDelete"
          @toggle-public="handleTogglePublic"
        />
      </div>

      <!-- 分页 -->
      <div v-if="myApps.totalRow && myApps.totalRow > 0" class="pagination-wrapper">
        <a-pagination
          v-model:current="myAppsQuery.pageNum"
          v-model:pageSize="myAppsQuery.pageSize"
          :total="myApps.totalRow"
          :show-size-changer="false"
          @change="loadMyApps"
        />
      </div>
    </section>

    <!-- 精选应用区域 -->
    <section class="featured-apps-section">
      <div class="section-header">
        <h2 class="section-title">精选案例</h2>
        <a-button type="link" @click="loadFeaturedApps">
          <ReloadOutlined />
          刷新
        </a-button>
      </div>

      <div class="apps-grid">
        <AppCard
          v-for="app in featuredApps.records"
          :key="app.id"
          :app="app"
          :featured="true"
          :show-user="true"
          @chat="handleAppChat"
          @view="handleAppView"
          @edit="handleAppEdit"
          @delete="handleAppDelete"
          @view-user="handleViewUser"
        />
      </div>

      <!-- 分页 -->
      <div v-if="featuredApps.totalRow && featuredApps.totalRow > 0" class="pagination-wrapper">
        <a-pagination
          v-model:current="featuredAppsQuery.pageNum"
          v-model:pageSize="featuredAppsQuery.pageSize"
          :total="featuredApps.totalRow"
          :show-size-changer="false"
          @change="loadFeaturedApps"
        />
      </div>
    </section>

    <!-- 用户信息弹窗 -->
    <UserInfoModal v-model:visible="userModalVisible" :user="selectedUser" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  RocketOutlined,
  ReloadOutlined,
  AppstoreOutlined,
  ShoppingOutlined,
  TeamOutlined,
  ToolOutlined
} from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/loginUser'
import { addApp, listMyAppByPage, listAllFeaturedAppByPage, updateAppPublicStatus } from '@/api/yingyongjiekou'
import AppCard from '@/components/AppCard.vue'
import UserInfoModal from '@/components/UserInfoModal.vue'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 用户输入
const userPrompt = ref('')
const creating = ref(false)

// 统计数据
const stats = reactive({
  appsCreated: 1234,
  activeUsers: 567,
  deployments: 890,
  satisfaction: 98
})

// 快速模板
interface QuickTemplate {
  id: number
  name: string
  icon: unknown
}

const quickTemplates: QuickTemplate[] = [
  { id: 1, name: '电商网站', icon: ShoppingOutlined },
  { id: 2, name: '企业官网', icon: AppstoreOutlined },
  { id: 3, name: '团队协作', icon: TeamOutlined },
  { id: 4, name: '工具应用', icon: ToolOutlined }
]

// 我的应用查询参数
const myAppsQuery = reactive({
  pageNum: 1,
  pageSize: 20,
  appName: '',
  isFeatured: false
})

// 精选应用查询参数
const featuredAppsQuery = reactive({
  pageNum: 1,
  pageSize: 20,
  appName: '',
  isFeatured: true
})

// 应用数据
const myApps = reactive<API.PageAppVO>({
  records: [],
  totalRow: 0,
  pageNumber: 1,
  pageSize: 20,
  totalPage: 0,
  optimizeCountQuery: true
})

const featuredApps = reactive<API.PageAppVO>({
  records: [],
  totalRow: 0,
  pageNumber: 1,
  pageSize: 20,
  totalPage: 0,
  optimizeCountQuery: true
})

// 用户信息弹窗
const userModalVisible = ref(false)
const selectedUser = ref<API.UserBasicVO | null>(null)

// 创建应用
const handleCreateApp = async () => {
  if (!userPrompt.value.trim()) {
    message.warning('请输入应用描述')
    return
  }

  if (!loginUserStore.loginUser.id) {
    message.warning('请先登录')
    router.push('/user/login')
    return
  }

  creating.value = true
  try {
    const response = await addApp({
      initPrompt: userPrompt.value
    })

    if (response.data.code === 200 && response.data.data) {
      message.success('应用创建成功')
      // 跳转到对话页面
      router.push(`/app/chat/${response.data.data}`)
    } else {
      message.error(response.data.message || '创建失败')
    }
  } catch (error) {
    message.error('创建应用失败')
    console.error(error)
  } finally {
    creating.value = false
  }
}

// 选择模板
const handleSelectTemplate = (template: QuickTemplate) => {
  const prompts: Record<string, string> = {
    电商网站: '创建一个现代化的电商网站，包含商品展示、购物车、用户登录等功能',
    企业官网: '创建一个专业的企业官网，包含公司介绍、产品服务、联系方式等页面',
    团队协作: '创建一个团队协作平台，包含任务管理、文件共享、团队沟通等功能',
    工具应用: '创建一个实用的工具应用，比如计算器、待办事项、笔记等'
  }

  userPrompt.value = prompts[template.name] || template.name
}

// 加载我的应用
const loadMyApps = async () => {
  if (!loginUserStore.loginUser.id) return

  try {
    const response = await listMyAppByPage(myAppsQuery)
    if (response.data.code === 200 && response.data.data) {
      const data = response.data.data
      // 确保 totalRow 是数字类型
      if (data.totalRow) {
        data.totalRow = Number(data.totalRow)
      }
      Object.assign(myApps, data)
    }
  } catch (error) {
    console.error('加载我的应用失败:', error)
  }
}

// 加载精选应用
const loadFeaturedApps = async () => {
  try {
    const response = await listAllFeaturedAppByPage(featuredAppsQuery)
    if (response.data.code === 200 && response.data.data) {
      const data = response.data.data
      // 确保 totalRow 是数字类型
      if (data.totalRow) {
        data.totalRow = Number(data.totalRow)
      }
      Object.assign(featuredApps, data)
    }
  } catch (error) {
    console.error('加载精选应用失败:', error)
  }
}

// 应用操作处理
const handleAppChat = (app: API.AppVO) => {
  console.log('点击应用对话，应用ID:', app.id)
  console.log('准备跳转到:', `/app/chat/${app.id}`)
  if (app.id) {
    router.push(`/app/chat/${app.id}`)
  }
}

const handleAppView = (app: API.AppVO) => {
  console.log('点击应用详情，应用ID:', app.id)
  console.log('准备跳转到:', `/app/detail/${app.id}`)
  if (app.id) {
    router.push(`/app/detail/${app.id}`)
  }
}

const handleAppEdit = (app: API.AppVO) => {
  if (app.id) {
    router.push(`/app/edit/${app.id}`)
  }
}

const handleAppDelete = () => {
  // 这里可以添加删除确认逻辑
  message.info('删除功能待实现')
}

const handleViewUser = (user: API.UserBasicVO) => {
  selectedUser.value = user
  userModalVisible.value = true
}

// 公开状态切换
const handleTogglePublic = async (app: API.AppVO, isPublic: boolean) => {
  if (!app.id) return
  
  try {
    const response = await updateAppPublicStatus({
      appId: app.id,
      isPublic: isPublic ? 1 : 0
    })

    if (response.data.code === 200) {
      loadMyApps() // 刷新列表
    } else {
      message.error(response.data.message || '更新失败')
    }
  } catch (error) {
    message.error('更新公开状态失败')
    console.error(error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadMyApps()
  loadFeaturedApps()
})
</script>

<style scoped>
.home-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.hero-section {
  padding: 80px 0;
  color: white;
}

.hero-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
}

.hero-content {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 60px;
  align-items: center;
}

.hero-title {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 24px;
  line-height: 1.2;
}

.gradient-text {
  background: linear-gradient(45deg, #ff6b6b, #4ecdc4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.hero-description {
  font-size: 18px;
  line-height: 1.6;
  margin-bottom: 40px;
  opacity: 0.9;
}

.prompt-input-section {
  margin-bottom: 32px;
}

.input-container {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.prompt-input {
  border: none;
  background: transparent;
  color: white;
  font-size: 16px;
  resize: none;
}

.prompt-input::placeholder {
  color: rgba(255, 255, 255, 0.7);
}

.input-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 16px;
}

.char-count {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
}

.create-btn {
  height: 48px;
  padding: 0 32px;
  font-size: 16px;
  border-radius: 8px;
}

.quick-templates {
  margin-top: 24px;
}

.templates-label {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.8);
  margin-bottom: 12px;
}

.template-tags {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.template-tag {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.template-tag:hover {
  background: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

.hero-visual {
  display: flex;
  justify-content: center;
  align-items: center;
}

.code-preview {
  width: 100%;
  max-width: 500px;
}

.code-window {
  background: #1e1e1e;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
}

.window-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background: #2d2d2d;
  border-bottom: 1px solid #404040;
}

.window-controls {
  display: flex;
  gap: 8px;
  margin-right: 16px;
}

.control {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.control.red {
  background: #ff5f56;
}
.control.yellow {
  background: #ffbd2e;
}
.control.green {
  background: #27ca3f;
}

.window-title {
  color: #ccc;
  font-size: 14px;
}

.code-content {
  padding: 20px;
  position: relative;
}

.code-block {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #d4d4d4;
}

.code-comment {
  color: #6a9955;
}
.code-keyword {
  color: #569cd6;
}
.code-string {
  color: #ce9178;
}
.code-function {
  color: #dcdcaa;
}
.code-tag {
  color: #569cd6;
}
.code-attr {
  color: #9cdcfe;
}

.typing-cursor {
  display: inline-block;
  width: 2px;
  height: 20px;
  background: #4ecdc4;
  animation: blink 1s infinite;
  margin-left: 4px;
}

.stats-section {
  padding: 60px 0;
  background: white;
}

.stats-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 40px;
}

.stat-item {
  text-align: center;
}

.stat-number {
  font-size: 36px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 16px;
  color: #666;
}

.my-apps-section,
.featured-apps-section {
  padding: 60px 0;
  background: #f8f9fa;
}

.my-apps-section {
  background: white;
}

.section-header {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32px;
}

.section-title {
  font-size: 32px;
  font-weight: bold;
  color: #1a1a1a;
  margin: 0;
}

.apps-grid {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
}

.pagination-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px;
  display: flex;
  justify-content: center;
  margin-top: 40px;
}

@keyframes blink {
  0%,
  50% {
    opacity: 1;
  }
  51%,
  100% {
    opacity: 0;
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hero-content {
    grid-template-columns: 1fr;
    gap: 40px;
  }

  .hero-title {
    font-size: 32px;
  }

  .stats-container {
    grid-template-columns: repeat(2, 1fr);
    gap: 24px;
  }

  .apps-grid {
    grid-template-columns: 1fr;
  }

  .section-title {
    font-size: 24px;
  }
}

@media (max-width: 480px) {
  .hero-container {
    padding: 0 16px;
  }

  .stats-container {
    grid-template-columns: 1fr;
  }

  .input-footer {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .create-btn {
    width: 100%;
  }
}
</style>
